from rest_framework import serializers

from users.models import UserCollect
from users.serializers import UserDetailSerializer, UserPartInfoSerializer
from .models import Spit, SpitComments


class SpitListSerializer(serializers.ModelSerializer):
    """吐槽首页"""
    class Meta:
        model = Spit
        fields = ('id', 'content', 'create_time', 'like_count', 'comment_count')


class SpitDetailSerializer(serializers.ModelSerializer):
    """吐槽详情页"""
    author = UserPartInfoSerializer()

    class Meta:
        model = Spit
        fields = ('id', 'author', 'content', 'create_time', 'like_count', 'comment_count')


class SpitCommentsListSerializer(serializers.ModelSerializer):
    """吐槽详情页评论列表"""
    author = UserPartInfoSerializer()

    class Meta:
        model = SpitComments
        fields = ('id', 'author', 'spit', 'content', 'create_time', 'like_count', 'parent')


class SpitCollectionsSerializer(serializers.ModelSerializer):
    """收藏吐槽序列化器"""
    class Meta:
        model = UserCollect
        fields = '__all__'

    def validate(self, attrs):
        user_id = attrs['user']
        spit_id = attrs['spit']

        spcl = UserCollect.objects.filter(user=user_id, spit=spit_id)
        if not spcl:
            return attrs
        else:
            spcl.delete()
            raise serializers.ValidationError('取消收藏')
